<?php
namespace Api\Controller;

use Api\Common\BaseController;

/**
 * Class Image 图像类,上传和获取头像,banner图,礼物图片等.
 * @package Api\Controller
 */
class ImageController extends BaseController
{
    private $Max_size = 3145728;
    private $Action_list = array("avatar","banner","gift");
    private $exts = array(
        "avatar"  =>  array('jpg', 'png', 'jpeg'), // 头像允许上传格式
        "gift"    =>  array("gif","jpg","png","swf","jpeg"), // banner图允许上传格式.
        "banner" => array('jpg', 'png', 'jpeg'),
    );// 允许上传的文件后缀格式.
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 上传的统一入口，
     */
    public function upload()
    {
        if (!empty($_POST['pic'])      && // 图片的二进制流文件.
            !empty($_POST['size'])     && // 图片的大小.
            !empty($_POST['action'])   && // 执行的动作,avatar,banner,gift
            !empty($_POST["fileName"])    // 文件名(包含后缀).
        ) {
            $action = $_POST["action"];
            if (!in_array($action, $this->Action_list)) {
                $this->responseFail("不存在该动作");
            }
            // 带上传图片的二进制数据流.
            $file = base64_decode($_POST['pic']);
            $fileName = $_POST['fileName'];
            $nameInfo = explode(".", $fileName);
            $baseName = $nameInfo[0]; // 待保存的文件名，不包含后缀
            $ext = $nameInfo[1];
            $fileSize = $_POST['size'];
            if (!in_array($ext, $this->exts[$action])) {
                $this->responseFail("不支持的格式");
            }
            if ($fileSize > $this->Max_size) {
                $this->responseFail("上传文件过大");
            }
            $rootPath = realpath(APP_PATH) . "/../"; //项目根目录的绝对路径.
            switch ($action) {
                case "avatar":
                    $uid = (int)$baseName;
                    $filePath = "/style/avatar/" . substr(md5($uid), 0, 3) . "/";
                    $path = $rootPath . $filePath;
                    $saveSuccessOrFail = $this->saveFile($file, $path, $fileName);
                    // 上传成功,生成三张缩略图.
                    if ($saveSuccessOrFail) {
                        $fileNameOfSmall = $uid . "_small.jpg";   // 小图
                        $fileNameOfMiddle = $uid . "_middle.jpg"; // 中图.
                        $fileNameOfBig = $uid . "_big.jpg";       // 大图.
                        // 实例化图像处理.
                        $image = new \Think\Image();
                        // 打开图像.
                        $image->open($path . $fileName);
                        //将原图处理生成三个规格的图片,默认等比缩放.
                        $image->thumb(200, 200)->save($path.$fileNameOfSmall);
                        $image->thumb(120, 120)->save($path.$fileNameOfMiddle);
                        $image->thumb(48, 48)->save($path.$fileNameOfBig);
                        $domain = C("DOMAIN");
                        $url = $domain . $filePath . $fileNameOfMiddle;
                        $this->responseSuccess($url);
                    } else {
                        $this->responseFail("上传失败");
                    }
                    break;
                case "banner":
                    $prefix = date("Y-m");
                    $filePath = "/style/rollpic/" . $prefix . "/";
                    $path = $rootPath . $filePath;
                    $saveSuccessOrFail = $this->saveFile($file, $path, $fileName);
                    if ($saveSuccessOrFail) {
                        $url = C("DOMAIN") . $filePath . $fileName;
                        $this->responseSuccess($url);
                    } else {
                        $this->responseFail("上传失败");
                    }
                    break;
                case "gift":
                    $prefix = "gift";
                    $filePath = "/style/images/" . $prefix . "/";
                    $path = $rootPath . $filePath;
                    $saveSuccessOrFail = $this->saveFile($file, $path, $fileName);
                    if ($saveSuccessOrFail) {
                        $url = C("DOMAIN") . $filePath . $fileName;
                        $this->responseSuccess($url);
                    } else {
                        $this->responseFail("上传失败");
                    }
                    break;
            }
        } else {
            $this->responseFail("缺少必须参数");
        }
    }

    /**
     * 保存文件.
     * @param $file
     * @param $path
     * @param $fileName
     * @return bool
     */
    private function saveFile($file,$path,$fileName)
    {
        if (!is_dir($path)) {
            mkdir($path,0777,true);
        }
        // 保存二进制图片.
        file_put_contents($path.$fileName,$file);
        if (file_exists($path.$fileName)) {
            return true;
        } else {
           return false;
        }
    }
}